let path = require('path');
let fs = require('fs');
let vm = require('vm');

function Module(id){
    this.id = id;
    this.exports = {};
}
// 缓存
Module._cache = Object.create(null);

Module.wrap = function(script){
    return `(function (exports,require,module,__finame,__dirname){
        ${script}
    })`
}

Module._extensions = {
    '.js'(module){
        let content = fs.readFileSync(module.id,'utf8');
        let fnStr = Module.wrap(content);
        let fn = vm.runInThisContext(fnStr);
        fn.call(module.exports,module.exports,req,module);
    },
    '.json'(module){
        let content = fs.readFileSync(module.id,'utf8');
        module.exports = content;
    }
}

//自动识别后缀
Module._resolveFilename = function(filename){
    let ext = path.extname(filename);
    if (ext) {
        if (Object.keys(Module._extensions).indexOf(ext) != -1) {
            let realPath = path.resolve(__dirname,filename);
            try {
                fs.accessSync(realPath);
                return {realPath,ext};
            } catch (e) {
                console.log(1);
                return false;
            }
        }else{
            console.log(2);
            return false;
        }
    }else{
        for(let ext in Module._extensions){
            let name = filename+ext;
            let realPath = path.resolve(__dirname,name);
            try {
                fs.accessSync(realPath);
                return {realPath,ext};
            } catch (e) {}
        }
        return false;
    }
    
}

function req(p){
    //自动后缀查找
    let {realPath,ext} = Module._resolveFilename(p);
    //缓存
    let cacheModule = Module._cache[realPath];
    if (cacheModule) {
        return cacheModule.exports;
    }else{
        let module = new Module(realPath);
        Module._extensions[ext](module);
        Module._cache[realPath] = module;
        return module.exports;
    }
    
    
}
